package com.laoma.gateway.predicate;

import cn.hutool.core.date.DateUtil;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.function.Predicate;

@Component
public class AccessTimeRoutePredicateFactory extends AbstractRoutePredicateFactory<AccessTimeRoutePredicateFactory.Config> {
    public AccessTimeRoutePredicateFactory() {
        super(AccessTimeRoutePredicateFactory.Config.class);
    }

    // 将配置文件中的值按返回集合的顺序，赋值给配置类
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(new String[]{"fromTime", "toTime"});
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        // 创建网关断言对象
        return new Predicate<ServerWebExchange>() {
            // 检查
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                // 判断当前时间是否在设置的时间段内.这里直接用时分合成的数值和当前时间的数值做对比；
                //8:30=830， 17:30=1730 ，比如当前时间为10:20=1020
                String start = config.getFromTime();
                String end = config.getToTime();
                if(StringUtils.defaultString(start).matches("[0-9]{1,2}:[0-9]{2}") &&
                        StringUtils.defaultString(end).matches("[0-9]{1,2}:[0-9]{2}")) {
                    int fromTime = Integer.valueOf(start.replaceAll(":",""));
                    int toTime = Integer.valueOf(end.replaceAll(":",""));
                    int curTime = Integer.parseInt(DateUtil.format(new Date(), "HHmm"));
                    if(fromTime<=curTime && curTime<=toTime) {
                        return true;
                    }
                }
                return false;
            }
        };
    }

    // 配置类，属性用于接收配置文件中的值
    @Validated
    @Data
    public static class Config {
        private String fromTime;
        private String toTime;
    }
}
